{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Auto-tuning a convolutional network for NVIDIA GPU\n",
    "\n",
    "**Author**: *Lianmin Zheng*, *Eddie Yan*\n",
    "\n",
    "Auto-tuning for specific devices and workloads is critical for getting the\n",
    "best performance. This is a tutorial on how to tune a whole convolutional\n",
    "network for NVIDIA GPU.\n",
    "\n",
    "The operator implementation for NVIDIA GPU in TVM is written in template form.\n",
    "The template has many tunable knobs (tile factor, unrolling, etc).\n",
    "We will tune all convolution and depthwise convolution operators\n",
    "in the neural network. After tuning, we produce a log file which stores\n",
    "the best knob values for all required operators. When the TVM compiler compiles\n",
    "these operators, it will query this log file to get the best knob values.\n",
    "\n",
    "We also released pre-tuned parameters for some NVIDIA GPUs. You can go to\n",
    "[NVIDIA GPU Benchmark](https://github.com/apache/incubator-tvm/wiki/Benchmark#nvidia-gpu)\n",
    "to see the results.\n",
    "\n",
    "\n",
    "## Install dependencies\n",
    "\n",
    "To use the autotvm package in tvm, we need to install some extra dependencies.\n",
    "(change \"3\" to \"2\" if you use python2):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/ --user psutil xgboost==1.0.2 tornado\n",
    "!pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/ --user antlr4-python3-runtime"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make TVM run faster during tuning, it is recommended to use cython\n",
    "as FFI of tvm. In the root directory of tvm, execute:\n",
    "\n",
    "    pip3 install --user cython\n",
    "    sudo make cython3\n",
    "\n",
    "Now return to python code. Import packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.insert(0, \"tvm_upstream/python\")\n",
    "sys.path.insert(0, \"tvm_upstream/topi/python\")\n",
    "\n",
    "import os\n",
    "import numpy as np\n",
    "import tvm\n",
    "from tvm import te\n",
    "from tvm import autotvm\n",
    "from tvm import relay\n",
    "import tvm.relay.testing\n",
    "from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner\n",
    "from tvm.contrib.util import tempdir\n",
    "import tvm.contrib.graph_runtime as runtime\n",
    "import xgboost"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define Network\n",
    "\n",
    "First we need to define the network in relay frontend API.\n",
    "We can load some pre-defined network from :code:`tvm.relay.testing`.\n",
    "We can also load models from MXNet, ONNX and TensorFlow."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_network(name, batch_size):\n",
    "    \"\"\"Get the symbol definition and random weight of a network\"\"\"\n",
    "    input_shape = (batch_size, 3, 224, 224)\n",
    "    output_shape = (batch_size, 1000)\n",
    "\n",
    "    if \"resnet\" in name:\n",
    "        n_layer = int(name.split('-')[1])\n",
    "        mod, params = relay.testing.resnet.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n",
    "    elif \"vgg\" in name:\n",
    "        n_layer = int(name.split('-')[1])\n",
    "        mod, params = relay.testing.vgg.get_workload(num_layers=n_layer, batch_size=batch_size, dtype=dtype)\n",
    "    elif name == 'mobilenet':\n",
    "        mod, params = relay.testing.mobilenet.get_workload(batch_size=batch_size, dtype=dtype)\n",
    "    elif name == 'squeezenet_v1.1':\n",
    "        mod, params = relay.testing.squeezenet.get_workload(batch_size=batch_size, version='1.1', dtype=dtype)\n",
    "    elif name == 'inception_v3':\n",
    "        input_shape = (1, 3, 299, 299)\n",
    "        mod, params = relay.testing.inception_v3.get_workload(batch_size=batch_size, dtype=dtype)\n",
    "    elif name == 'mxnet':\n",
    "        # an example for mxnet model\n",
    "        from mxnet.gluon.model_zoo.vision import get_model\n",
    "        block = get_model('resnet18_v1', pretrained=True)\n",
    "        mod, params = relay.frontend.from_mxnet(block, shape={'data': input_shape}, dtype=dtype)\n",
    "        net = mod[\"main\"]\n",
    "        net = relay.Function(net.params, relay.nn.softmax(net.body), None, net.type_params, net.attrs)\n",
    "        mod = tvm.IRModule.from_expr(net)\n",
    "    else:\n",
    "        raise ValueError(\"Unsupported network: \" + name)\n",
    "\n",
    "    return mod, params, input_shape, output_shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set Tuning Options\n",
    "\n",
    "Before tuning, we apply some configurations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#### DEVICE CONFIG ####\n",
    "target = tvm.target.cuda()\n",
    "\n",
    "#### TUNING OPTION ####\n",
    "network = 'resnet-18'\n",
    "log_file = \"%s.log\" % network\n",
    "dtype = 'float32'\n",
    "\n",
    "tuning_option = {\n",
    "    'log_filename': log_file,\n",
    "\n",
    "    'tuner': 'xgb',\n",
    "    'n_trial': 2000,\n",
    "    'early_stopping': 600,\n",
    "\n",
    "    'measure_option': autotvm.measure_option(\n",
    "        builder=autotvm.LocalBuilder(timeout=10),\n",
    "        #runner=autotvm.LocalRunner(number=20, repeat=3, timeout=4, min_repeat_ms=150),\n",
    "        runner=autotvm.RPCRunner(\n",
    "            '1080ti',  # change the device key to your key\n",
    "            '0.0.0.0', 9190,\n",
    "            number=20, repeat=3, timeout=4, min_repeat_ms=150)\n",
    "    ),\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Begin Tuning\n",
    "\n",
    "Now we can extract tuning tasks from the network and begin tuning.\n",
    "Here, we provide a simple utility function to tune a list of tasks.\n",
    "This function is just an initial implementation which tunes them in sequential order.\n",
    "We will introduce a more sophisticated tuning scheduler in the future."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can skip the implementation of this function for this tutorial.\n",
    "def tune_tasks(tasks,\n",
    "               measure_option,\n",
    "               tuner='xgb',\n",
    "               n_trial=1000,\n",
    "               early_stopping=None,\n",
    "               log_filename='tuning.log',\n",
    "               use_transfer_learning=True):\n",
    "    # create tmp log file\n",
    "    tmp_log_file = log_filename + \".tmp\"\n",
    "    if os.path.exists(tmp_log_file):\n",
    "        os.remove(tmp_log_file)\n",
    "\n",
    "    for i, tsk in enumerate(reversed(tasks)):\n",
    "        prefix = \"[Task %2d/%2d] \" %(i+1, len(tasks))\n",
    "\n",
    "        # create tuner\n",
    "        if tuner == 'xgb' or tuner == 'xgb-rank':\n",
    "            tuner_obj = XGBTuner(tsk, loss_type='rank')\n",
    "        elif tuner == 'ga':\n",
    "            tuner_obj = GATuner(tsk, pop_size=100)\n",
    "        elif tuner == 'random':\n",
    "            tuner_obj = RandomTuner(tsk)\n",
    "        elif tuner == 'gridsearch':\n",
    "            tuner_obj = GridSearchTuner(tsk)\n",
    "        else:\n",
    "            raise ValueError(\"Invalid tuner: \" + tuner)\n",
    "\n",
    "        if use_transfer_learning:\n",
    "            if os.path.isfile(tmp_log_file):\n",
    "                tuner_obj.load_history(autotvm.record.load_from_file(tmp_log_file))\n",
    "\n",
    "        # do tuning\n",
    "        tsk_trial = min(n_trial, len(tsk.config_space))\n",
    "        tuner_obj.tune(n_trial=tsk_trial,\n",
    "                       early_stopping=early_stopping,\n",
    "                       measure_option=measure_option,\n",
    "                       callbacks=[\n",
    "                           autotvm.callback.progress_bar(tsk_trial, prefix=prefix),\n",
    "                           autotvm.callback.log_to_file(tmp_log_file)\n",
    "                       ])\n",
    "\n",
    "    # pick best records to a cache file\n",
    "    autotvm.record.pick_best(tmp_log_file, log_filename)\n",
    "    os.remove(tmp_log_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Finally, we launch tuning jobs and evaluate the end-to-end performance.\n",
    "def tune_and_evaluate(tuning_opt):\n",
    "    # extract workloads from relay program\n",
    "    print(\"Extract tasks...\")\n",
    "    mod, params, input_shape, out_shape = get_network(network, batch_size=1)\n",
    "    tasks = autotvm.task.extract_from_program(mod[\"main\"], target=target,\n",
    "                                              params=params,\n",
    "                                              ops=(relay.op.get(\"nn.conv2d\"),))\n",
    "\n",
    "    # run tuning tasks\n",
    "    print(\"Tuning...\")\n",
    "    tune_tasks(tasks, **tuning_opt)\n",
    "\n",
    "    # compile kernels with history best records\n",
    "    with autotvm.apply_history_best(log_file):\n",
    "        print(\"Compile...\")\n",
    "        with relay.build_config(opt_level=3):\n",
    "            graph, lib, params = relay.build_module.build(\n",
    "                mod, target=target, params=params)\n",
    "\n",
    "        # export library\n",
    "        tmp = tempdir()\n",
    "        filename = \"net.tar\"\n",
    "        lib.export_library(tmp.relpath(filename))\n",
    "\n",
    "        # load parameters\n",
    "        ctx = tvm.context(str(target), 0)\n",
    "        module = runtime.create(graph, lib, ctx)\n",
    "        data_tvm = tvm.nd.array((np.random.uniform(size=input_shape)).astype(dtype))\n",
    "        module.set_input('data', data_tvm)\n",
    "        module.set_input(**params)\n",
    "\n",
    "        # evaluate\n",
    "        print(\"Evaluate inference time cost...\")\n",
    "        ftimer = module.module.time_evaluator(\"run\", ctx, number=1, repeat=600)\n",
    "        prof_res = np.array(ftimer().results) * 1000  # convert to millisecond\n",
    "        print(\"Mean inference time (std dev): %.2f ms (%.2f ms)\" %\n",
    "              (np.mean(prof_res), np.std(prof_res)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We do not run the tuning in our webpage server since it takes too long.\n",
    "Uncomment the following line to run it by yourself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Cannot connect to tracker ('0.0.0.0', 9190), retry in 5 secs...\n"
     ]
    }
   ],
   "source": [
    "# tune_and_evaluate(tuning_option)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sample Output\n",
    "\n",
    "The tuning needs to compile many programs and extract feature from them.\n",
    "So a high performance CPU is recommended. One sample output is listed below.\n",
    "It takes about 4 hours to get the following output on a 32T AMD Ryzen Threadripper.\n",
    "The tuning target is NVIDIA 1080 Ti.\n",
    "(You can see some errors during compilation. If the tuning is not stuck, it is okay.)\n",
    "\n",
    "    Extract tasks...\n",
    "    Tuning...\n",
    "    [Task  1/12]  Current/Best:  541.83/3570.66 GFLOPS | Progress: (960/2000) | 1001.31 s Done.\n",
    "    [Task  2/12]  Current/Best:    0.56/ 803.33 GFLOPS | Progress: (704/2000) | 608.08 s Done.\n",
    "    [Task  3/12]  Current/Best:  103.69/1141.25 GFLOPS | Progress: (768/2000) | 702.13 s Done.\n",
    "    [Task  4/12]  Current/Best: 2905.03/3925.15 GFLOPS | Progress: (864/2000) | 745.94 sterminate called without an active exception\n",
    "    [Task  4/12]  Current/Best: 2789.36/3925.15 GFLOPS | Progress: (1056/2000) | 929.40 s Done.\n",
    "    [Task  5/12]  Current/Best:   89.06/1076.24 GFLOPS | Progress: (704/2000) | 601.73 s Done.\n",
    "    [Task  6/12]  Current/Best:   40.39/2129.02 GFLOPS | Progress: (1088/2000) | 1125.76 s Done.\n",
    "    [Task  7/12]  Current/Best: 4090.53/5007.02 GFLOPS | Progress: (800/2000) | 903.90 s Done.\n",
    "    [Task  8/12]  Current/Best:    4.78/1272.28 GFLOPS | Progress: (768/2000) | 749.14 s Done.\n",
    "    [Task  9/12]  Current/Best: 1391.45/2325.08 GFLOPS | Progress: (992/2000) | 1084.87 s Done.\n",
    "    [Task 10/12]  Current/Best: 1995.44/2383.59 GFLOPS | Progress: (864/2000) | 862.60 s Done.\n",
    "    [Task 11/12]  Current/Best: 4093.94/4899.80 GFLOPS | Progress: (224/2000) | 240.92 sterminate called without an active exception\n",
    "    [Task 11/12]  Current/Best: 3487.98/4909.91 GFLOPS | Progress: (480/2000) | 534.96 sterminate called without an active exception\n",
    "    [Task 11/12]  Current/Best: 4636.84/4912.17 GFLOPS | Progress: (1184/2000) | 1381.16 sterminate called without an active exception\n",
    "    [Task 11/12]  Current/Best:   50.12/4912.17 GFLOPS | Progress: (1344/2000) | 1602.81 s Done.\n",
    "    [Task 12/12]  Current/Best: 3581.31/4286.30 GFLOPS | Progress: (736/2000) | 943.52 s Done.\n",
    "    Compile...\n",
    "    Evaluate inference time cost...\n",
    "    Mean inference time (std dev): 1.07 ms (0.05 ms)\n",
    "\n",
    "As a reference baseline, the time cost of MXNet + TensorRT on resnet-18 is 1.30ms. So we are a little faster."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scale up measurement by using multiple devices\n",
    "\n",
    "If you have multiple devices, you can use all of them for measurement.\n",
    "TVM uses the RPC Tracker to manage distributed devices.\n",
    "The RPC Tracker is a centralized master node. We can register all devices to\n",
    "the tracker. For example, if we have 10 GPU cards, we can register all of them\n",
    "to the tracker, and run 10 measurements in parallel, accelerating the tuning process.\n",
    "\n",
    "To start an RPC tracker, run this command on the host machine. The tracker is\n",
    "required during the whole tuning process, so we need to open a new terminal for\n",
    "this command:\n",
    "\n",
    "    python -m tvm.exec.rpc_tracker --host=0.0.0.0 --port=9190\n",
    "\n",
    "The expected output is\n",
    "\n",
    "    INFO:RPCTracker:bind to 0.0.0.0:9190\n",
    "\n",
    "Then open another new terminal for the RPC server. We need to start one server\n",
    "for each dedicated device. We use a string key to distinguish the types of devices.\n",
    "You can pick a name you like.\n",
    "(Note: For rocm backend, there are some internal errors with the compiler,\n",
    "we need to add `--no-fork` to the argument list.)\n",
    "\n",
    "    python -m tvm.exec.rpc_server --tracker=0.0.0.0:9190 --key=1080ti\n",
    "\n",
    "After registering devices, we can confirm it by querying rpc_tracker\n",
    "\n",
    "    python -m tvm.exec.query_rpc_tracker --host=0.0.0.0 --port=9190\n",
    "\n",
    "For example, if we have four 1080ti, two titanx and one gfx900, the output can be\n",
    "\n",
    "\n",
    "    Queue Status\n",
    "    ----------------------------------\n",
    "    key          total  free  pending\n",
    "    ----------------------------------\n",
    "    1080ti       4      4     0\n",
    "    titanx       2      2     0\n",
    "    gfx900       1      1     0\n",
    "    ----------------------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_mxnet_p36",
   "language": "python",
   "name": "conda_mxnet_p36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
